package tk.mybatis.springboot.service.impl;

import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.springboot.common.KeCongResult;
import tk.mybatis.springboot.common.TaskUtil;
import tk.mybatis.springboot.entity.CustomizedTask;
import tk.mybatis.springboot.entity.LogTask;
import tk.mybatis.springboot.mapper.LogMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogExtendService {

    public static final String URL_STATUS_TASK = TaskUtil.PREV_URL+"api/fms/taskStatus";

    @Autowired
    LogMapper logMapper;

    public List<LogTask> selectLogByPage(int page,int count){
        int offset =(page - 1) * count;
        RowBounds rowBounds = new RowBounds(offset,count);
        List<LogTask> logTasks = logMapper.selectLogByPage(rowBounds);
        for(int i=0;i<logTasks.size();i++){
            LogTask logTask = addTaskStatus(logTasks.get(i));
            logTasks.set(i,logTask);
        }
        return logTasks;
    }

    private LogTask addTaskStatus(LogTask emptyItem){
        CloseableHttpResponse httpResponse = null;
        Map<String,String> param = new HashMap<>();
        param.put("TaskNo",emptyItem.TaskNo);
        try {
            httpResponse = TaskUtil.httpPost(URL_STATUS_TASK, param);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = httpResponse.getEntity();
                String jsonString = EntityUtils.toString(entity);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                emptyItem.task_status = keCongResult.Status==null?"finish":keCongResult.Status;
                return emptyItem;
            }else{
                System.out.println("访问任务状态网络不通");
            }
        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        }finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return null;
    }
}
